package com.selangshiwo.sina.biz;

import java.security.NoSuchAlgorithmException;
import com.selangshiwo.Util;
import com.selangshiwo.sina.httpclient.SinaHttpClient;
import com.selangshiwo.sina.requst.SSOLoginRequestPack;
import com.selangshiwo.sina.result.ResultPack;
import com.selangshiwo.sina.result.SSOLoginResultPack;

public class SSOLoginBiz implements IBaseHttpBiz{

	private String uName = "";
	private String uPwd = "";
	private String nonce = "";
	private int servertime = -1 ;
	private String pcid = "" ;
	
	private String deName = "";	//编码后的用户名
	private String dePwd = "";	//编码后的密码
	
	private String strWeiboUrl = "";	//微博认证地址
	
	public SSOLoginBiz(String uName , String uPwd
			,String nonce , int servertime , String pcid){
		this.setuName(uName);
		this.setNonce(nonce);
		this.setServertime(servertime);
		this.setPcid(pcid);
		this.setuPwd(uPwd);
	}
	
	public void setPcid(String pcid){
		this.pcid = pcid ;
	}
	
	public String getNonce() {
		return nonce;
	}

	public void setNonce(String nonce) {
		this.nonce = nonce;
	}

	public int getServertime() {
		return servertime;
	}

	public void setServertime(int servertime) {
		this.servertime = servertime;
	}

	public String getuName() {
		return uName;
	}


	public void setuName(String uName) {
		this.uName = uName;
		this.deName = Util.base42Encode((uName.replace("@", "%40").getBytes()));
	}


	public String getuPwd() {
		return uPwd;
	}

	public void setuPwd(String uPwd) {
		this.uPwd = uPwd;
		try {
			this.dePwd = hexShaPwd();
		} catch (NoSuchAlgorithmException e) {
			Util.err("加密密码异常!");
			e.printStackTrace();
		}
	}

	private void setStrWeiboUrl(String url){
		this.strWeiboUrl = url ;
	}
	
	public String getStrWeiboUrl(){
		return this.strWeiboUrl ;
	}
	
	private String hexShaPwd() throws NoSuchAlgorithmException{
		
		if("".equals(getuPwd()) == true){
			throw new NullPointerException("未设置密码!");
		}
		
		return Util.hex_sha1(Util.hex_sha1(Util.hex_sha1(this.getuPwd())) + this.getServertime() + this.getNonce());
		
	}
	
	@Override
	public ResultPack run() {
		Util.debug("*SSO登录准备+++++++++++++++++++");
		SSOLoginRequestPack request = new SSOLoginRequestPack(this.deName, this.dePwd, this.nonce , 
					""+this.servertime, this.pcid );		

		Util.debug("*开始处理业务....");
		SSOLoginResultPack result =  (SSOLoginResultPack) SinaHttpClient.getInstance().postRequest(request, SSOLoginResultPack.class) ;
		
		this.setStrWeiboUrl(result.getWeiboUrl());
		
		return result ;
	}

}
